interface Command {
  id: string;
  title: string;
  callback: (...args: any[]) => any;
}

const commands = new Map<string, Command>();

export const commandService = {
  /**
   * Registers a command with the system.
   * @returns A disposable object to unregister the command.
   */
  register(id: string, title: string, callback: (...args: any[]) => any) {
    if (commands.has(id)) {
      console.warn(`Command '${id}' is already registered. Overwriting.`);
    }
    commands.set(id, { id, title, callback });
    console.log(`Command registered: ${id} ('${title}')`);
    return {
      dispose: () => {
        commands.delete(id);
        console.log(`Command unregistered: ${id}`);
      }
    };
  },

  /**
   * Executes a registered command.
   */
  execute<T>(id: string, ...args: any[]): Promise<T> {
    const command = commands.get(id);
    if (command) {
      try {
        const result = command.callback(...args);
        return Promise.resolve(result);
      } catch (error) {
        console.error(`Error executing command '${id}':`, error);
        return Promise.reject(error);
      }
    } else {
      console.error(`Command '${id}' not found.`);
      return Promise.reject(new Error(`Command '${id}' not found.`));
    }
  },

  /**
   * Returns a list of all registered commands.
   */
  getCommands(): Command[] {
    return Array.from(commands.values());
  }
};